import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        socket=new Socket(serverIP,serverPort);
    }

    public void start(){
        System.out.println("start!");
        try(InputStream inputStream=socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream()){
            Scanner scannerConsole=new Scanner(System.in);
            Scanner scannerSocket=new Scanner(inputStream);
            PrintWriter writer=new PrintWriter(outputStream);

            while(true){
                //1. 从控制台读取请求
                System.out.print(">");
                if(!scannerConsole.hasNext()){
                    break;
                }
                String request=scannerConsole.next();

                //2.发送请求
                writer.println(request);
                writer.flush();
                //3.接收响应
                String response =scannerSocket.next();

                //打印
                System.out.println(response);
            }
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client=new TcpEchoClient("127.0.0.1",10200);
        client.start();
    }
}
